package com.party.admin.web.controller.enterpriseservice;

import com.party.admin.biz.enterpriseservice.EpServiceBizService;
import com.party.admin.biz.enterpriseservice.EpServiceCategoryBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.enterpriseservice.EpServiceOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.enterpriseservice.EpCategory;
import com.party.core.model.enterpriseservice.EpService;
import com.party.core.model.enterpriseservice.EpServiceCategory;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.enterpriseservice.IEpServiceCategoryService;
import com.party.core.service.enterpriseservice.IEpServiceService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @program: party
 * @description: 企业服务控制器
 * @author: Hua Qunhao
 * @create: 2019-01-08 16:45
 */
@Controller
@RequestMapping(value = "/epService/epService")
public class EnterpriseServiceController {

    @Autowired
    private IEpServiceService epServiceService;

    @Autowired
    private EpServiceBizService epServiceBizService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private IEpServiceCategoryService epServiceCategoryService;

    @Autowired
    private EpServiceCategoryBizService epServiceCategoryBizService;


    Logger logger = LoggerFactory.getLogger(EnterpriseServiceController.class);

    /**
     * 服务列表
     *
     * @param epService
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView epServiceList(EpService epService, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("enterpriseservice/epServiceList");

        Map<String, Object> params = CommonInput.appendParams(commonInput);

        if (StringUtils.isNotEmpty(epService.getCategoryId())) {
            params.put("categoryId", epService.getCategoryId());
        }
        List<EpCategory> epCategories = epServiceCategoryBizService.getEpCategoryListAll();

        List<EpService> epServices = epServiceService.weblistPage(epService, params, page);
        List<EpServiceOutput> epServiceOutputs = LangUtils.transform(epServices, input -> {
            EpServiceOutput articleOutput = EpServiceOutput.transform(input);

            String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "epservice");
            // 详情二维码
            String fileName = "epservice_info_" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            articleOutput.setQrCodeUrl(qrCodeUrl);
            return articleOutput;
        });


        mv.addObject("input", commonInput);
        mv.addObject("epService", epService);
        mv.addObject("epServices", epServiceOutputs);
        mv.addObject("epCategories", epCategories);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 服务列表-发布/编辑
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "epServiceView")
    public ModelAndView articleForm(String id) {
        ModelAndView mv = new ModelAndView("enterpriseservice/epServiceView");

        if (StringUtils.isNotEmpty(id)) {
            EpService epService = epServiceService.get(id);
            if (StringUtils.isNotEmpty(epService.getContent())) {
                epService.setContent(StringUtils.unescapeHtml4Video2Iframe(epService.getContent()));
            }
            List<EpCategory> categorys = epServiceCategoryService.queryCategoryListbyServiceId(epService.getId());
            mv.addObject("epService", epService);
            mv.addObject("categoryList", categorys);
        }
        return mv;
    }

    /**
     * 跳转至详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "epServiceDetail")
    public ModelAndView epServiceDetail(String id) {
        ModelAndView mv = new ModelAndView("enterpriseservice/epServiceDetail");
        EpService epService = epServiceService.get(id);

        if (StringUtils.isNotEmpty(epService.getContent())) {
            epService.setContent(StringUtils.unescapeHtml4Video2Iframe(epService.getContent()));
        }
        mv.addObject("epService", epService);
        return mv;
    }

    /**
     * 服务保存
     *
     * @param epService
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(EpService epService, BindingResult result) {

        String memberId = RealmUtils.getCurrentUser().getId();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        if (StringUtils.isEmpty(epService.getCategoryList())) {
            return AjaxResult.error("分类列表不能为空");
        }
        epService.setCreateBy(memberId);
        try {
            try {
                epServiceCategoryBizService.updateGoodsNum("update", epService.getId(), epService.getCategoryList());
            } catch (Exception e) {
                logger.error("更新分类统计数异常", e);
            }
            //更新数据
            epServiceBizService.saveOrupdateEpservice(epService);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存服务异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存服务异常");
        }
    }


    /**
     * 删除服务
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            try {
                EpService epService = epServiceService.get(id);
                epServiceCategoryBizService.updateGoodsNum("delete", epService.getId(), "");
            } catch (Exception e) {
                logger.error("更新分类统计数异常", e);
            }
            epServiceService.delete(id);
            epServiceCategoryService.deleteEpCategoryBycIdandsid(new EpServiceCategory(null, id));

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("服务删除异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("服务删除异常");
        }
    }
}
